<!DOCTYPE html>
<html>
<head>
    <title>YOLOv5 Object Detection</title>
</head>
<body>
    <h1>YOLOv5 Object Detection</h1>

    <h2>Upload Image</h2>
    <form action="/detect" method="POST" enctype="multipart/form-data">
        <input type="file" name="image" required><br><br>

        <input type="submit" value="Detect Objects">
    </form>

    <h2>Detection Result</h2>
    <div id="result"></div>

    <script>
        function detectObjects() {
            // 获取图像文件
            var imageFile = document.querySelector('input[type="file"]').files[0];

            // 创建 FormData 对象并添加图像文件
            var formData = new FormData();
            formData.append('image', imageFile);

            // 发送 POST 请求到 /detect 路由
            fetch('/detect', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(result => {
                // 显示检测结果
                displayDetectionResult(result);
            })
            .catch(error => console.error(error));
        }

        function displayDetectionResult(result) {
            var resultDiv = document.getElementById('result');
            resultDiv.innerHTML = '';

            if (result.length > 0) {
                for (var i = 0; i < result.length; i++) {
                    var detection = result[i];
                    var classLabel = detection.class;
                    var confidence = detection.confidence;
                    var bbox = detection.bbox;

                    var detectionText = 'Class: ' + classLabel + ', Confidence: ' + confidence.toFixed(2) + '<br>';
                    resultDiv.innerHTML += detectionText;

                    // 可选：在图像上绘制边界框
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    var img = new Image();
                    img.src = URL.createObjectURL(imageFile);
                    img.onload = function() {
                        canvas.width = img.width;
                        canvas.height = img.height;
                        ctx.drawImage(img, 0, 0);
                        ctx.strokeStyle = 'red';
                        ctx.lineWidth = 2;
                        ctx.beginPath();
                        ctx.rect(bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]);
                        ctx.closePath();
                        ctx.stroke();
                        resultDiv.appendChild(canvas);
                    };
                }
            } else {
                resultDiv.innerHTML = 'No objects detected.';
            }
        }
    </script>
</body>
</html>